<template>
  <div class="revenue-statistics">
    <!-- 筛选条件 -->
    <el-form :inline="true" :model="filterForm" class="filter-form">
      <el-form-item label="统计时间">
        <el-date-picker
          v-model="filterForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :shortcuts="dateShortcuts"
        />
      </el-form-item>
      <el-form-item label="收入类型">
        <el-select v-model="filterForm.type" placeholder="请选择收入类型" clearable>
          <el-option label="报名费" value="registration" />
          <el-option label="补考费" value="reexam" />
          <el-option label="其他费用" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleFilter">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="card in statisticsCards" :key="card.title">
        <el-card class="statistics-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon" :style="{ backgroundColor: card.color }">
              <el-icon>
                <component :is="card.icon" />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value">
                <span class="number">{{ card.value }}</span>
                <span class="unit">{{ card.unit }}</span>
              </div>
              <div class="card-trend">
                <span :class="['trend', card.trend > 0 ? 'up' : 'down']">
                  {{ Math.abs(card.trend) }}%
                  <el-icon>
                    <CaretTop v-if="card.trend > 0" />
                    <CaretBottom v-else />
                  </el-icon>
                </span>
                <span class="trend-text">较上月</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 收入趋势图 -->
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入趋势</span>
              <el-radio-group v-model="trendTimeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>
      </el-col>

      <!-- 收入构成 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入构成</span>
            </div>
          </template>
          <div class="chart-container" ref="compositionChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入明细表格 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>收入明细</span>
          <div class="header-operations">
            <el-button type="primary" @click="exportDetail">导出明细</el-button>
          </div>
        </div>
      </template>
      <el-table
        :data="revenueList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="type" label="收入类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ row.typeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="studentName" label="学员姓名" width="120" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import {
  Money,
  Wallet,
  CreditCard,
  Ticket,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  type: ''
})

// 统计卡片数据
const statisticsCards = [
  {
    title: '总收入',
    value: '268,550',
    unit: '元',
    icon: Money,
    color: '#409EFF',
    trend: 12.5
  },
  {
    title: '报名收入',
    value: '235,800',
    unit: '元',
    icon: Wallet,
    color: '#67C23A',
    trend: 15.2
  },
  {
    title: '补考收入',
    value: '18,750',
    unit: '元',
    icon: CreditCard,
    color: '#E6A23C',
    trend: -5.8
  },
  {
    title: '其他收入',
    value: '14,000',
    unit: '元',
    icon: Ticket,
    color: '#F56C6C',
    trend: 8.3
  }
]

// 图表相关
const trendTimeRange = ref('month')
const trendChartRef = ref(null)
const compositionChartRef = ref(null)

let trendChart = null
let compositionChart = null

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const revenueList = ref([
  {
    date: '2024-03-15',
    orderNo: 'DD202403150001',
    type: 'registration',
    typeName: '报名费',
    studentName: '张三',
    amount: 5800,
    paymentMethod: '微信支付',
    status: 'completed',
    statusName: '已完成',
    operator: '王经理',
    remark: 'C1自动档报名费'
  },
  {
    date: '2024-03-15',
    orderNo: 'DD202403150002',
    type: 'reexam',
    typeName: '补考费',
    studentName: '李四',
    amount: 150,
    paymentMethod: '支付宝',
    status: 'completed',
    statusName: '已完成',
    operator: '李会计',
    remark: '科目二补考费'
  }
])

// 获取类型标签样式
const getTypeTagType = (type) => {
  const types = {
    registration: 'success',
    reexam: 'warning',
    other: 'info'
  }
  return types[type] || ''
}

// 获取状态标签样式
const getStatusTagType = (status) => {
  const types = {
    completed: 'success',
    pending: 'warning',
    refunded: 'info',
    cancelled: 'danger'
  }
  return types[status] || ''
}

// 初始化趋势图
const initTrendChart = () => {
  trendChart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总收入', '报名收入', '补考收入', '其他收入']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '金额（元）'
    },
    series: [
      {
        name: '总收入',
        type: 'line',
        smooth: true,
        data: [15000, 18000, 22000, 19000, 25000, 26800, 28000]
      },
      {
        name: '报名收入',
        type: 'line',
        smooth: true,
        data: [12000, 15000, 18000, 16000, 21000, 23000, 24000]
      },
      {
        name: '补考收入',
        type: 'line',
        smooth: true,
        data: [2000, 2000, 2500, 2000, 2500, 2300, 2500]
      },
      {
        name: '其他收入',
        type: 'line',
        smooth: true,
        data: [1000, 1000, 1500, 1000, 1500, 1500, 1500]
      }
    ]
  }
  trendChart.setOption(option)
}

// 初始化构成图
const initCompositionChart = () => {
  compositionChart = echarts.init(compositionChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '收入构成',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 235800, name: '报名收入' },
          { value: 18750, name: '补考收入' },
          { value: 14000, name: '其他收入' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  compositionChart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  compositionChart?.resize()
}

// 筛选
const handleFilter = () => {
  // TODO: 实现筛选逻辑
  console.log('筛选条件：', filterForm)
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  handleFilter()
}

// 导出明细
const exportDetail = () => {
  // TODO: 实现导出逻辑
  ElMessage.success('导出成功')
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleFilter()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleFilter()
}

onMounted(() => {
  // 初始化图表
  initTrendChart()
  initCompositionChart()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  trendChart?.dispose()
  compositionChart?.dispose()
})
</script>

<style scoped>
.revenue-statistics {
  padding: 20px;
}

.filter-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.statistics-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.card-icon :deep(.el-icon) {
  font-size: 24px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  margin-bottom: 8px;
}

.card-value .number {
  font-size: 24px;
  font-weight: bold;
  margin-right: 4px;
}

.card-value .unit {
  font-size: 14px;
  color: #909399;
}

.card-trend {
  font-size: 12px;
}

.trend {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
}

.trend.up {
  color: #67c23a;
}

.trend.down {
  color: #f56c6c;
}

.trend-text {
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.detail-card {
  margin-bottom: 20px;
}

.header-operations {
  display: flex;
  gap: 12px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>